<template>
  <div class="cart">

    <van-nav-bar :class="{'navBar':isActive}" style="font-size: 16px;font-weight: bold;">
      <template #left>
        <span class="left-text">购物车</span>
      </template>
    </van-nav-bar>

    <!--没有物品时显示-->
    <div class="no-good" v-if="flag">
      <div>购物车空空的，快去购物吧~</div>
      <van-button class="btn" to="/" type="primary">去首页</van-button>
    </div>

    <!--所有订单-->
    <div class="cartList">
      <!--用于记录选择的项-->
      <van-checkbox-group v-model="checkedGood">
        <!-- 用于包裹滑动单元格-->
        <div class="check-item" v-for="item in cartList" :key="item.id">
          <van-swipe-cell class="swipe-cell">
            <van-checkbox :key="item.id" :name="item.id"></van-checkbox>
            <van-card :thumb="item.imageUrl" :title="item.name">
              <div class="desc" slot="desc">{{ item.description }}</div>
              <div class="price" slot="price">{{ item.salePrice | moneyFormat }}</div>
              <div class="footer" slot="footer">
                <span @click="addCount(item,item.count)">
                  <van-button size="mini">+</van-button>
                </span>
                <span class="count">
                  <span class="count-edit">{{ item.count }}</span>
                </span>
                <span @click="reduceCount(item,item.count)">
                  <van-button size="mini">-</van-button>
                </span>
              </div>
            </van-card>
            <template #right>
              <van-button text="删除" type="danger" class="delete-button" height="100%"
                          @click="deleteCartInfo(item.id,item.userId)"/>
            </template>
          </van-swipe-cell>
        </div>
      </van-checkbox-group>
    </div>

    <!--提交数据-->
    <van-submit-bar button-text="提交订单" label="合计" :price="totalPrice *100" @submit="submitData()"
                    v-if="this.cartList.length>0">
          <span class="selectAll">
            <van-checkbox v-model="checkedAll">{{ this.checkedAll ? "全不选" : "全选" }}</van-checkbox>
          </span>
    </van-submit-bar>
  </div>
</template>

<script>
import filter from "../../filters/filter";

export default {
  name: "CartIndex",
  data() {
    return {
      cartList: [],
      checkedGood: [],
      flag: false,
      isActive: false
    };
  },

  created() {
    this.getCartList();
  },

  mounted() {
    let height = document.documentElement.clientHeight || document.body.clientHeight;
    let html = document.getElementsByClassName("cart")[0];
    html.style.height = height + "px";
  },

  filters: {
    moneyFormat(money) {
      return filter.moneyFormat(money);
    }
  },

  computed: {
    totalPrice() {
      return this.cartList.reduce((total, item) => {
        //查询时的是复选框选中的一项 如果没有就是 -1；
        return total + (this.checkedGood.indexOf(item.id) !== -1 ? item.salePrice * item.count : 0);
      }, 0);
    },

    checkedAll: {
      get() {
        return this.cartList.length ? this.cartList.length === this.checkedGood.length : false;
      },
      set(val) {
        if (val) {
          this.checkedGood = this.cartList.map(item => item.id);
        } else {
          this.checkedGood = [];
        }
      }
    }
  },

  methods: {

    // 获取购物车列表
    async getCartList() {
      if (!this.$store.getters.user.userId) {
        this.$toast.fail("请先登录");
        return;
      }
      let res = await this.$axios.post(this.$api.getUserCartList, {id: this.$store.getters.user.userId});
      if (res.status === 200 && res.data.code === 200) {
        this.cartList = res.data.data;
        if (this.cartList.length > 0) {
          this.isActive = true;
          this.flag = false;
        } else {
          this.flag = true;
        }
      } else {
        this.$toast.fail(res.data.message);
      }
    },

    // 控制购买的数量减少
    reduceCount(goods, count) {
      if (!count && count !== 0) {
        this.$toast({position: "bottom", message: "数值不正确~"});
        return;
      }

      if (count <= 1) {
        this.$toast({position: "bottom", message: "不能再少了~"});
        return;
      }
      count--;
      goods.count = count;
      this.updateCartCountThrottle(goods.id, count);
    },
    // 控制购买的数量增加
    addCount(goods, count) {
      if (!count && count !== 0) {
        this.$toast({position: "bottom", message: "数值不正确~"});
        return;
      }
      if (count >= 10) {
        this.$toast({position: "bottom", message: "限购10本~"});
        return;
      }
      count++;
      goods.count = count;
      this.updateCartCountThrottle(goods.id, count);
    },

    // 更新购物车数量
    updateCartCountThrottle(id, count) {
      this.updateCartCount(id, count);
    },
    async updateCartCount(id, count) {
      let res = await this.$axios.post(this.$api.updateCartCount, {goodsId: id, count})
      if (res.status === 200 && res.data.code === 200) {
        setTimeout(() => {
          this.getCartList();
        }, 150);
      } else {
        this.$toast({position: "bottom", message: res.data.message});
      }
    },

    // 删除
    async deleteCartInfo(goodsId, userId) {
      let res = await this.$axios.post(this.$api.deleteCart, {userId: userId, goodsId: goodsId});
      if (res.status === 200 && res.data.code === 200) {
        await this.getCartList();
      } else {
        this.$toast({position: "bottom", message: res.data.message});
      }
    },

    //实现数据提交的实现购买
    submitData() {
      if (!this.checkedGood.length) {
        this.$notify({message: "请选择要购买的商品"});
        return false;
      }
      // 提交时先清除数据
      if (localStorage.getItem("selectedGoodsList")) {
        localStorage.removeItem("selectedGoodsList");
      }

      localStorage.setItem("selectedGoodsList", JSON.stringify(this.checkedGood));
      this.$router.push({path: "/submitOrders", query: {type: 2}});
    }

  }
};
</script>

<style lang="less" scoped>
.cart {
  height: 100%;
  background-color: #fafafa;

  .van-hairline--bottom::after {
    border-bottom-width: 0;
  }

  .navBar {
    background-color: #fafafa;

    .left-text {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .no-good {
    position: absolute;
    width: 220px;
    text-align: center;
    color: #666;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .btn {
      margin-top: 16px;
    }
  }

  /*有商品时*/

  .cartList {
    background-color: #fafafa;

    padding: 0 8px 100px 8px;

    .check-item {
      margin-bottom: 10px;
      border-radius: 8px;
      overflow: hidden;

      .swipe-cell {
        position: relative;
        background-color: white;

        .van-checkbox {
          position: absolute;
          top: 50%;
          left: 8px;
          transform: translateY(-50%);
        }

        .van-card {
          background-color: #ffffff;
          margin-top: 0;
          margin-left: 30px;

          .van-card__bottom {
            height: 20px;
          }

          .van-card__price {
            height: 20px;
          }

          .price {
            color: #F08860;
          }

          .desc {
            color: #7d7e80;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .footer {
            display: flex;
            flex-direction: row-reverse;
            align-items: center;
            margin-top: 5px;

            .count {
              margin: 0 .4rem;

              .count-edit {
                padding: 0 10px 3px 10px;
                font-size: 14px;
                text-align: center;
                background-color: #fff;
                border-bottom: 1px solid #f6b539;
              }
            }

            .van-button {
              min-width: 30px;
              margin: 0;
            }
          }
        }

        .van-button--normal {
          height: 100%;
        }
      }
    }
  }

  .van-submit-bar {
    bottom: 50px;
  }
}
</style>
